from flask import Flask
from flask import jsonify
from flask import request

app = Flask(__name__)  # 创建对象


# 静态路由，构建url与函数绑定
@app.route('/users', methods=['GET'])
def hello_world():
    return '姓名&nbsp;&nbsp;&nbsp;电话<br/>' \
           '张三&nbsp;&nbsp;&nbsp;17788889999<br/>' \
           '李四&nbsp;&nbsp;&nbsp; 17788887777'


users_info = {
    '1001': ['213456', '张三', 1000],
    '1002': ['213456', '李四', 1000],
    '1003': ['213456', '王五', 1000],
    '1004': ['213456', '赵柳', 1000], }


# 动态路由-jsonify-get请求
@app.route('/users/<string:account>', methods=['GET'])
def get_user(account):
    account = request.args.get('account')
    if account:
        if account in users_info:
            info = users_info[account]
            # return f'尊敬的{info[1]}先生，您的账户余额为：{info[2]:.2f}元'
            return jsonify({"code": 10000, "message": "success",
                            "data": {"name": info[1], "balance": info[-1]}})
        else:
            # return '账户不存在'
            return jsonify({"code": 10001, "message": "account does not exist"})
    else:
        return jsonify({"code": 10002, "message": "param error"})


# 动态路由-post请求
@app.route('/login', methods=['POST'])
def login():
    account = request.form.get('account')
    passwd = request.values.get('password')
    if account and passwd:  # 检查请求参数是否正确
        if account in users_info:  # 检查账号是否存在
            info = users_info[account]
            if passwd == info[0]:  # 检查密码是否正确
                return jsonify({"code": 10000, "message": "success"})
            else:
                return jsonify({"code": 10003, "message": "pawword error"})
        else:
            return jsonify({"code": 10002, "message": "param error"})
    else:
        return jsonify({"code": 10002, "message": "param error"})


if __name__ == '__main__':
    # app.run(debug=True) #默认方式启动
    app.run(host='127.0.0.1', prot=80, debug=1)
